<?php
namespace app\portal\controller;

use cmf\controller\HomeBaseController;
use app\admin\service\ApiService;
use think\Db;

class QuestController extends HomeBaseController
{

	//评价中心页面
	public function index()
	{

		$img = Db::name('img')->find(7);
		$this->assign('img',$img);

		$user_id = cmf_get_current_user_id();

		$data = Db::name('quest')
		->order("start_time desc")
		->where(['delete_time'=>0])
		->select()
		->toArray();
		
		$data_user = Db::name('quest_answer')
		->where(['user_id'=>$user_id])
		->select()
		->toArray();

		for ($i=0,$count = count($data); $i < $count; $i++) { 
			$data[$i]['is_part'] = 0;
			foreach ($data_user as $key => $value) {
				if ($data[$i]['id'] == $value['quest_id']) {
					$data[$i]['is_part'] = 1;
				}
			}
		}

		$this->assign('data',$data);
		return $this->fetch();
	}
	//评价提交页面
	public function detail()
	{
		$user_id = cmf_get_current_user_id();

		$id = $this->request->param('id',0,'intval');

		$data = Db::name('quest')->find($id);

		if ($data == null) {
			$this->error('页面不存在');
		}

		$data_title = Db::name('quest_title')
		->where(['qid'=>$id])
		->select();

		$this->assign('data_title',$data_title);
		$this->assign('data',$data);
		return $this->fetch();
	}
	//评价统计页面
	public function count(){

		$user_id = cmf_get_current_user_id();
		$id = $this->request->param('id',0,'intval');
		
		$data = Db::name('quest')->find($id);
		if (null == $data) {
			$this->error('页面不存在');
		}
		$data_user = Db::name('quest_answer')
		->where(['quest_id'=>$id])
		->select();

		$data_title = Db::name('quest_title')
		->where(['qid'=>$id])
		->select();
		$count_title = count($data_title)*count($data_user);

		$data['answer1'] = $data['answer2']= $data['answer3'] = 0;
		foreach ($data_user as $key => $value) {
		
			$answer_array = json_decode($value['answer'],true);
            $count_array = array_count_values($answer_array);
            $data['answer1'] += $count_array[1];
            $data['answer2'] += $count_array[2];
            $data['answer3'] += $count_array[3];
		}
		$data['answer1'] = $count_title?round($data['answer1']/$count_title,2)*100:0;
		$data['answer2'] = $count_title?round($data['answer2']/$count_title,2)*100:0;
		$data['answer3'] = $count_title?round($data['answer3']/$count_title,2)*100:0;
		$this->assign('data_user',$data_user);
		$this->assign('data',$data);
		return $this->fetch();
	}

	//留言诉求接口
	public function addPost()
	{
		$data = $this->request->param();

		$data['user_id'] = cmf_get_current_user_id();;
		$data['time'] = time();
		$data['answer'] = [];
		$data['answer'] = json_encode($data['arr']);

		unset($data['arr']);
		$res = Db::name('quest_answer')->insert($data);
		if ($res) {
			$result = json_encode(array('msg'=>"提交成功",'status'=>1,'url'=>"http://".$_SERVER['HTTP_HOST'].url('index')));
		}else{
			$result = json_encode(array('msg'=>"提交失败",'status'=>0));
		}
		echo $result; return;
	}	
}